﻿/*
 * DavidLee 基于zyUpload by zhangyan 2014-06-21   QQ : 623585268
 * 进行layui模块扩展实现多图片上传组件
 */
layui.define(['jquery', 'layer', 'popup', 'http', 'lodash'], function (exports) {
	"use strict";
    var version = "1.0.0";
	var $ = layui.jquery || layui.$;
	var layer = layui.layer;
	var popup = layui.popup;
	var http = layui.http;
	var lodash = layui.lodash;

	var ZYFILE = function () {
		var fileNum = 0;					// 代表文件总个数，因为涉及到继续添加，所以下一次添加需要在它的基础上添加索引
		//默认配置
		var DEFAULT_OPT = {
			elemId: "#uploadForm",			//上传Form表单(Container)DOM Id
			uploadUrl: "",					// 上传action路径
			//上传提交后台数据包：JSON数据对象：
			//已上传后台文件成功后， File更换为后台返回文件路径
			//新选择(待上传)文件 File为file对象
			//用以区分已上传文件数据及待上传数据
			//格式如下： 
			// {
			//		Id:  1,			//文件对象存储数据库键值，0则新添加
			//		File: fileObj,  //input type=file选择获取的文件对象
			//		Useage: "",		//上传文件分类用途，默认DEFAULT
			//      Title: "",      //上传文件显示标题，可空
			//		Description: "",//上传文件显示详情，可空
			//		ImageLink: ""   //上传文件点击跳转链接，一般广告图用
			//      fileIndex: 0,   //文件下标，用于构造预览区html
			// }
			uploadDataList: [],
			/* 提供给外部的接口 以 onXXXX() 形式 与内部调用方法区分 */
			onFilterFile: function (files) { return files; },			// 提供给外部的过滤文件格式等的接口，外部需要把过滤后的文件返回
			onSelect: function (selectFileDatas, allFileDatas) { },		// 提供给外部获取选中的文件，供外部实现预览等功能  selectFile:当前选中的文件  allFiles:还没上传的全部文件
			onDelete: function (delFileData, remainFileDatas) { },		// 提供给外部获取删除的单个文件，供外部实现删除效果  file:当前删除的文件  files:删除之后的文件
			onProgress: function (fileData, loaded, total) { },			// 提供给外部获取单个文件的上传进度，供外部实现上传进度效果
			onSuccess: function (fileData) { },							// 提供给外部获取单个文件上传成功，供外部实现成功效果
			onFailure: function (fileData, responseInfo) { },			// 提供给外部获取单个文件上传失败，供外部实现失败效果
			onDragOver: function () { },		
			onDragLeave: function () { }
		};
		this.options = {};					
		// 初始化
		this.init = function (params) {  // 初始化方法，在此给选择、上传按钮绑定事件
			var self = this;
			self.options = $.extend({}, DEFAULT_OPT, params);
			if (self.options.uploadDataList.length > 0) {
				layui.each(self.options.uploadDataList, function (index, item) {
					if (item.Id && typeof item.File === "string") {
						item.fileIndex = fileNum++;
					}
				});
			}
			const $zyUploadForm = $(self.options.elemId);
			//绑定文件托拽事件
			var $dragDrop = $zyUploadForm.find("#fileDragArea");
			if ($dragDrop.length > 0) {
				$dragDrop[0].addEventListener("dragover", function (e) {
					self.funDragHover(e);
				}, false);
				$dragDrop[0].addEventListener("dragleave", function (e) {
					self.funDragHover(e);
				}, false);
				$dragDrop[0].addEventListener("drop", function (e) {
					self.funGetFiles(e);
				}, false);
			}
			const $fileInput = $zyUploadForm.find("#zyUploadFile");
			//绑定文件选择事件
			if ($fileInput.length > 0) {
				// 绑定change事件
				$fileInput[0].addEventListener("change", function (e) {
					self.funGetFiles(e);
				}, false);
			}
			const $uploadSubmitBtn = $zyUploadForm.find("#fileSubmit");
			// 绑定文件上传按钮事件
			if ($uploadSubmitBtn.length > 0) {
				// 绑定click事件
				$uploadSubmitBtn.on("click", function (e) {
					self.funUploadFiles();
				});
			}
		};
		// 获得选中的文件 //文件拖放
		this.funDragHover = function (e) {
			e.stopPropagation();
			e.preventDefault();
			this.options[e.type === "dragover" ? "onDragOver" : "onDragLeave"].call(e.target);
			return this;
		};
		// 获取文件
		this.funGetFiles = function (e) {
			var self = this;
			// 取消鼠标经过样式
			this.funDragHover(e);
			// 从事件中获取选中的所有文件
			var files = e.target.files || e.dataTransfer.files;
			var filteredFiles = this.options.onFilterFile(files);
			if (filteredFiles.length > 0) {
				var newUploadFileDatas = [];
				layui.each(filteredFiles, function (index, file) {
					//注，不过滤重名文件，限制太死麻烦
					const fileData = {
						Id: 0, 
						File: file,
						Useage: "DEFAULT",
						Title: "",     
						Description: "",
						ImageLink: "",
						fileIndex: fileNum++
					}
					newUploadFileDatas.push(fileData);
				});
				self.options.uploadDataList = lodash.concat(self.options.uploadDataList, newUploadFileDatas);
				// 执行选择回调
				self.options.onSelect(newUploadFileDatas, self.options.uploadDataList);
				return true;
            }
			return false;
		};
		// 处理需要删除的文件  
		this.funDeleteFile = function (delFileIndex) {
			var delFileData = lodash.find(this.options.uploadDataList, ['fileIndex', delFileIndex]);
			if (delFileData !== undefined) {
				this.options.uploadDataList = lodash.reject(this.options.uploadDataList, ['fileIndex', delFileIndex]);
				this.options.onDelete(delFileData, this.options.uploadDataList);
			}
			else return false;

			console.info("文件删除成功，剩余文件列表:");
			console.info(this.options.uploadDataList);
			return true;
		};
		// 上传多个文件
		this.funUploadFiles = function () {
			var self = this;
			//已上传后台文件成功后， File更换为后台返回文件路径
			//新选择(待上传)文件 File为file对象
			//用以区分已上传文件数据及待上传数据
			var unUploadFiles = self.funGetUnuploadFiles();
			layui.each(unUploadFiles, function (k, v) {
				self.funUploadFile(v);
			});
		};
		// 上传单个文件
		this.funUploadFile = function (fileData) {
			var self = this; 
			var formData = new FormData();
			//参数封装至FormData
			layui.each(fileData, function (key, value) {
				if (key !== 'fileIndex') {
					value = typeof value === 'function' ? value() : value;
					formData.append(key, value);
                }
			});
			http.postForm(this.options.uploadUrl, formData, function (xhr) {
				//beforeSend
				if (xhr.upload) {
					xhr.upload.addEventListener("progress", function (e) {
						// 外部回调实现文件上传进度展示 
						self.options.onProgress(fileData, e.loaded, e.total);
					}, false);
				}
			}).done(
				function (response) {
					if (response.state && response.state === 200) {
						//upload api respond data as: {Id: mediaFileId, VirtualPath: mediaFileUrl}
						fileData.Id = response.data.Id;
						fileData.File = response.data.VirtualPath;
						self.options.uploadDataList = lodash.reject(self.options.uploadDataList, ['fileIndex', fileData.fileIndex]);
						self.options.uploadDataList.push(fileData);
						self.options.onSuccess(fileData);
					} else {
						self.options.onFailure(fileData, response);
                    }
				}
			).fail(
				function (error) {
					self.options.onFailure(fileData, error);
				}
			);
		};
		// 返回需要上传的文件
		this.funGetUnuploadFiles = function () {
			return lodash.filter(this.options.uploadDataList, function (o) {
				return o.File && lodash.isObject(o.File);
			});
		};		
	};

	var	zyUploadClass = function () {
		var defaults = {
			elem: "",						//挂载zyUpload组件的DOM Id
			acceptFiles: "*",				//上传文件接受的类型
			maxUploadCount: 8,				//最多一次能上传的文件数量
			maxUploadSize: 51200000,	    //单文件允许上传大小
			width: "700px",  				// 宽度
			height: "400px",  				// 宽度
			itemWidth: "140px",             // 文件项的宽度
			itemHeight: "120px",            // 文件项的高度
			url: "",  						// 上传文件的路径
			multiple: true,  				// 是否可以多个文件上传
			dragDrop: true,  				// 是否可以拖动上传文件
			del: true,  					// 是否可以删除文件
			edit: false,					// 是否可以编辑文件
			displayImage: false,  			// true: 当选择图片时在预览位置显示预览图
											// false: 默认，图片使用占位图显示
			values: [],						// 已上传文件数据，数据格式参见ZYFILE.uploadDataList
			/* 提供给外部的接口方法 */
			onSelect: function (selectFileDatas, allFileDatas) { },		// 提供给外部获取选中的文件，供外部实现预览等功能  selectFile:当前选中的文件  allFiles:还没上传的全部文件
			onDelete: function (delFileData, remainFileDatas) { return true; },	// 提供给外部获取删除的单个文件，供外部实现删除效果  file:当前删除的文件  files:删除之后的文件
			onSuccess: function (fileData) { },							// 提供给外部获取单个文件上传成功，供外部实现成功效果
			onFailure: function (fileData, responseInfo) { },			// 提供给外部获取单个文件上传失败，供外部实现失败效果
		};
		//允许显示图片类型
		var imageExtNames = ['bmp', 'gif', 'ico', 'jpg', 'jpeg', 'png', 'svg', 'webp'];
		var fileExtImages = [
			//文件预览不直接显示图片，而是根据上传文件扩展名使用对应的已准备好的
			//图片显示占位，如果是图片的话点击占位图显示预览大图
			'3ds', '7z', 'ai', 'asp', 'bin', 'bmp', 'com', 'css', 'csv', 'dll',
			'doc', 'docx', 'dwg', 'eps', 'exe', 'exel', 'file', 'fla', 'flv', 'gif',
			'html', 'ico', 'ini', 'iso', 'jpg', 'jpeg', 'js', 'mkv', 'mov', 'mp4',
			'nfo', 'obj', 'otf', 'pdf', 'pkg', 'png', 'ppt', 'rar', 'rtf', 'svg',
			'temp', 'ttf', 'txt', 'vcf', 'wav', 'wmv', 'xls', 'xlsx', 'xml', 'zip',
		];

		var allowedSize = 0;
		this.selectedFilesCount = 0;  //已选择（含待上传及已上传)的文件总数
		this.corePlugin = null;		 //ZYFILE
		this.options = {};
		this.$Elem = null;
		/*
		* 根据选择待上传的文件名（如 logo.png）获取文件扩展名
		* returns "" when names having no extension (e.g. myfile) or starting with . dot (e.g. .htaccess):
		* ""                            -->   ""
		* "name"                        -->   ""
		* "name.txt"                    -->   "txt"
		* ".htpasswd"                   -->   ""
		* "name.with.many.dots.myext"   -->   "myext"
		* If you care about the speed you may run the benchmark and check that the provided solutions are the fastest, while the short one is tremendously fast:
		* How the short one works:
		*	String.lastIndexOf method returns the last position of the substring (i.e. ".") in the given string (i.e. fname). If the substring is not found method returns -1.
		*	The "unacceptable" positions of dot in the filename are -1 and 0, which respectively refer to names with no extension (e.g. "name") and to names that start with dot (e.g. ".htaccess").
		*	Zero-fill right shift operator (>>>) if used with zero affects negative numbers transforming -1 to 4294967295 and -2 to 4294967294, which is useful for remaining the filename unchanged in the edge cases (sort of a trick here).
		*	String.prototype.slice extracts the part of the filename from the position that was calculated as described. If the position number is more than the length of the string method returns "".
		*	If you want more clear solution which will work in the same way (plus with extra support of full path), check the following extended version. This solution will be slower than previous one-liners but is much easier to understand.
		*	function getExtension(path) {
		*		var basename = path.split(/[\\/]/).pop(),  // extract file name from full path ...
		*		// (supports `\\` and `/` separators)
		*		pos = basename.lastIndexOf(".");       // get last position of `.`
		*		if (basename === "" || pos < 1)            // if file name is empty or ...
		*			return "";                             //  `.` not found (-1) or comes first (0)
		*		return basename.slice(pos + 1);            // extract extension ignoring `.`
		*	}
		*	console.log( getExtension("/path/to/file.ext") );
		*	// >> "ext"
		*	All functions should work in any web browser on the client side and can be used in the server side NodeJS code as well.
		*/
		this.getFileExtName = function (fname) {
			return fname.slice((fname.lastIndexOf(".") - 1 >>> 0) + 2);
		};

		this.render = function (options) {
			this.options = $.extend(defaults, options);
			allowedSize = (Math.round(this.options.maxUploadSize / (1024 * 1024)) / 100).toString() + 'MB';
			if (!options.url || options.url.length <= 0) {
				console.error("Please setup your UploadUrl");
				return this;
			}
			if (this.options.values.length > this.options.maxUploadCount) {
				console.error("maxUploadCount must greater than values count");
				return this;
			}
			this.$Elem = $(this.options.elem);
			if (this.$Elem == null || this.$Elem.length == 0) {
				console.error("Cannot find DOM Element by options.elem");
				return this;
			}
			this.corePlugin = new ZYFILE();
			this.createHtml();  // 创建组件html
			this.createCorePlug();  // 调用核心js	
			return this;
		};

		/**
			 * 功能：创建上传所使用的html
			 * 参数: 无
			 * 返回: 无
			 */
		this.createHtml = function () {
			var multiple = this.options.multiple
				? "multiple"
				: "";
			var html = '';

			if (this.options.dragDrop) {
				// 创建带有拖动的html
				html += '<form id="uploadForm" action="' + this.options.url + '" method="post" enctype="multipart/form-data">';
				html += '	<div class="upload_box">';
				html += '		<div class="upload_main">';
				html += '			<div class="upload_choose">';
				html += '				<div class="convent_choice">';
				html += '					<div class="andArea">';
				html += '						<div class="filePicker">点击选择文件</div>';
				html += '						<input id="zyUploadFile" type="file" size="30" name="fileselect[]" ' + multiple + ' accept="' + this.options.acceptFiles + '">';
				html += '					</div>';
				html += '				</div>';
				html += '				<span id="fileDragArea" class="upload_drag_area">或者将文件拖到此处</span>';
				html += '			</div>';
				html += '			<div class="status_bar">';
				if (this.options.values.length <= 0) {
					html += '			<div id="status_info" class="info">选中0个文件，共0B，还可上传' + this.options.maxUploadCount + '个文件。</div>';
				}
				else {
					html += '			<div id="status_info" class="info">选中' + this.options.values.length + '个文件，共0B，还可上传' + (this.options.maxUploadCount - this.options.values.length) + '个文件。</div>';
                }
				html += '				<div class="btns">';
				html += '					<div class="webuploader_pick">继续选择</div>';
				html += '					<div class="upload_btn">开始上传</div>';
				html += '				</div>';
				html += '			</div>';
				html += '			<div id="preview" class="upload_preview"></div>';
				html += '		</div>';
				html += '		<div class="upload_submit">';
				html += '			<button type="button" id="fileSubmit" class="upload_submit_btn">确认上传文件</button>';
				html += '		</div>';
				html += '		<div id="uploadInf" class="upload_inf"></div>';
				html += '	</div>';
				html += '</form>';
			} else {
				var imgWidth = parseInt(this.options.itemWidth.replace("px", "")) - 15;

				// 创建不带有拖动的html
				html += '<form id="uploadForm" action="' + this.options.url + '" method="post" enctype="multipart/form-data">';
				html += '	<div class="upload_box">';
				html += '		<div class="upload_main single_main">';
				html += '			<div class="status_bar">';
				if (this.options.values.length <= 0) {
					html += '			<div id="status_info" class="info">选中0个文件，共0B，还可上传' + this.options.maxUploadCount + '个文件。</div>';
				}
				else {
					html += '			<div id="status_info" class="info">选中' + this.options.values.length + '个文件，共0B，还可上传' + (this.options.maxUploadCount - this.options.values.length) + '个文件。</div>';
				}
				html += '				<div class="btns">';
				html += '					<input id="zyUploadFile" type="file" size="30" name="fileselect[]" ' + multiple + ' accept="' + this.options.acceptFiles + '">';
				html += '					<div class="webuploader_pick">选择文件</div>';
				html += '					<div class="upload_btn">开始上传</div>';
				html += '				</div>';
				html += '			</div>';
				html += '			<div id="preview" class="upload_preview">';
				html += '				<div class="add_upload">';
				html += '					<a style="height:' + this.options.itemHeight + ';width:' + this.options.itemWidth + ';" title="点击添加文件" id="rapidAddImg" class="add_imgBox" href="javascript:void(0)">';
				html += '						<div class="uploadImg" style="width:' + imgWidth + 'px">';
				html += '							<img class="upload_image" src="/lib/PearAdminLayui/component/pear/modules/zyUpload/images/add_img.png" style="width:expression(this.width > ' + imgWidth + ' ? ' + imgWidth + 'px : this.width)" />';
				html += '						</div>';
				html += '					</a>';
				html += '				</div>';
				html += '			</div>';
				html += '		</div>';
				html += '		<div class="upload_submit">';
				html += '			<button type="button" id="fileSubmit" class="upload_submit_btn">确认上传文件</button>';
				html += '		</div>';
				html += '		<div id="uploadInf" class="upload_inf"></div>';
				html += '	</div>';
				html += '</form>';
			}
			this.$Elem.append(html).css({ "width": this.options.width, "height": this.options.height });

			if (this.options.values.length > 0) {
				var self = this,
					previewHtml = "",
					index = 0;
				layui.each(self.options.values, function (index, data) {
					data.fileIndex = index++;
					previewHtml = self.funDisposePreviewHtml(data, null);
					self.funAppendPreviewHtml(data, null, previewHtml);
				});
            }

			// 初始化html之后绑定按钮的点击事件
			// 如果快捷添加文件按钮存在
			if ($(".filePicker").length > 0) {
				// 绑定选择事件
				$(".filePicker").on("click", function (e) {
					$("#zyUploadFile").click();
				});
			}

			// 绑定继续添加点击事件
			$(".webuploader_pick").on("click", function (e) {
				$("#zyUploadFile").click();
			});

			// 绑定上传点击事件
			var self = this;
			$(".upload_btn").on("click", function (e) {
				// 判断当前是否有文件需要上传
				if (self.corePlugin.funGetUnuploadFiles().length > 0) {
					$("#fileSubmit").click();
				} else {
					popup.failure("请选择待上传文件")
				}
			});
				
			// 如果快捷添加文件按钮存在
			if ($("#rapidAddImg").length > 0) {
				// 绑定添加点击事件
				$("#rapidAddImg").on("click", function (e) {
					$("#zyUploadFile").click();
				});
			}
		};
	
		/**
		 * 功能：显示统计信息和绑定继续上传和上传按钮的点击事件
		 * 参数: 无
		 * 返回: 无
		 */
		this.funSetStatusInfo = function (fileDatas) {
			var size = 0;
			var num = 0;
			$.each(fileDatas, function (k, v) {
				// 计算得到文件总大小
				if (lodash.isObject(v.File)) {
					size += v.File.size;
					num++;
                }
			});
			var uploadLeftCount = this.options.maxUploadCount - num;
			// 转化为kb和MB格式。文件的名字、大小、类型都是可以现实出来。
			if (size > 1024 * 1024) {
				size = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
			} else {
				size = (Math.round(size * 100 / 1024) / 100).toString() + 'KB';
			}

			// 设置内容
			$("#status_info").html("选中" + num + "个文件，共" + size + "，还可上传" + uploadLeftCount + "个文件。");
		};
		/**
		* 功能： 处理参数和格式上的预览html
		* 参数: files 本次选择的文件
		* 返回: 预览的html
		*/
		this.funDisposePreviewHtml = function (fileData, loadEvent) {
			var html = "";
			var imgWidth = parseInt(this.options.itemWidth.replace("px", "")) - 15;

			// 处理配置参数删除按钮
			var delHtml = "";
			if (this.options.del) {  // 显示删除按钮
				delHtml = '<span class="file_del" title="删除"></span>';
			}
			var editHtml = "";
			if (this.options.edit) {
				editHtml = '<span class="file_edit" title="编辑"></span>';
			}
			var self = this;
			var getImageSrc = function (fileName, loadEvent) {
				let fileImgSrc = "/lib/PearAdminLayui/component/pear/modules/zyUpload/images/fileType/";
				let fileExtName = self.getFileExtName(fileName);
				if (self.options.displayImage && lodash.indexOf(imageExtNames, fileExtName) >= 0)
					fileImgSrc = loadEvent == null ? fileName : loadEvent.target.result;
				else if (lodash.indexOf(fileExtImages, fileExtName))
					fileImgSrc = fileImgSrc + fileExtName.toLowerCase() + ".png";
				else fileImgSrc = fileImgSrc + "default.png";
				return fileImgSrc;
			};

			let fileImgSrc = "",
				fileName = "",
				fileIndex = fileData.fileIndex;
			if (lodash.isObject(fileData.File)) {
				//通过本地文件选择本地文件
				fileImgSrc = getImageSrc(fileData.File.name, loadEvent);
				fileName = fileData.File.name;
			} else { 
				//已有服务器端获取文件数据
				fileImgSrc = getImageSrc(fileData.File/*string image url*/, null);
				fileName = fileData.fileIndex;				
            }
			
			html += '<div id="uploadList_' + fileIndex + '" class="upload_append_list">';
			html += '	<div class="file_bar">';
			html += '		<div style="padding:5px;">';
			html += '			<p class="file_name">' + fileName + '</p>';
			html += delHtml;   // 删除按钮的html
			html += editHtml;  // 编辑按钮的html
			html += '		</div>';
			html += '	</div>';
			html += '	<a style="height:' + this.options.itemHeight + ';width:' + this.options.itemWidth + ';" href="javascript:;" class="imgBox">';
			html += '		<div class="uploadImg" style="width:' + imgWidth + 'px">';
			html += '			<img id="uploadImage_' + fileIndex + '" class="upload_image" src="' + fileImgSrc + '" style="width:expression(this.width > ' + imgWidth + ' ? ' + imgWidth + 'px : this.width)" />';
			html += '		</div>';
			html += '	</a>';
			html += '	<p id="uploadProgress_' + fileIndex + '" class="file_progress"></p>';
			html += '	<p id="uploadFailure_' + fileIndex + '" class="file_failure">上传失败，请重试</p>';
			html += '	<p id="uploadSuccess_' + fileIndex + '" class="file_success"></p>';
			html += '</div>';

			return html;
		};
		// 添加预览html
		this.funAppendPreviewHtml = function (fileData, loadEvent, html) {
			// 添加到添加按钮前
			if (this.options.dragDrop) {
				$("#preview").append(html);
			} else {
				$(".add_upload").before(html);
			}

			const $curPreview = $("#uploadList_" + fileData.fileIndex);
			// 图片上传的是图片还是其他类型文件
			var isImage = false;
			if (lodash.isObject(fileData.File)) {
				$curPreview.find("file_success").show();
				isImage = fileData.File.type.indexOf("image") == 0;
			} else {
				isImage = lodash.indexOf(imageExtNames, fileData.File/*string image url*/) >= 0;
			}
			if (isImage) {
				$curPreview.find("a.imgBox").on("click", function () {
					layer.open({
						type: 1,
						title: false,
						closeBtn: 2,
						area: ['auto'],
						skin: 'layui-layer-nobg', //没有背景色
						shadeClose: true,
						content: '<div id="previewImgLayer" style="width: 420px; height: 315px;">'
							+ '	<img src="' + (loadEvent == null ? fileData.File : loadEvent.target.result) + '" style="max-width: 100%;" >'
							+ '</div>'
					});
				});
			}
			//绑定操作栏滑动事件
			$curPreview.hover(
				function (e) {
					$(this).find(".file_bar").addClass("file_hover");
				}, function (e) {
					$(this).find(".file_bar").removeClass("file_hover");
				}
			);
			var self = this;
			//绑定操作栏按钮事件
			const $delBtn = $curPreview.find(".file_del");
			if ($delBtn.length > 0) {
				// 删除方法
				$delBtn.on("click", function () {
					self.corePlugin.funDeleteFile(fileData.fileIndex);
					return false;
				});
			}
			const $editBtn = $curPreview.find(".file_edit");
			if ($editBtn.length > 0) {
				// 编辑方法
				$editBtn.on("click", function () {
					// 调用编辑操作

					return false;
				});
			}
		};
		/**
		* 功能：过滤上传的文件格式等
		* 参数: files 本次选择的文件
		* 返回: 通过的文件
		*/
		this.funFilterEligibleFile = function (files) {
			var arrFiles = [];  // 替换的文件数组
			for (var i = 0, file; file = files[i]; i++) {
				if (file.size > this.options.maxUploadSize) {
					popup.failure('文件："' + file.name + '"超过允许上传大小, 最大允许上传文件：' + allowedSize);
				} else {
					//文件拖拽不受文件类型选择约束，在此过滤
					if (this.options.acceptFiles.length > 0 && this.options.acceptFiles !== "*") {
						const acceptExts = lodash.words(this.options.acceptFiles);
						const fileExt = this.getFileExtName(file.name);
						if (acceptExts && acceptExts.length > 0 && lodash.indexOf(acceptExts, fileExt) < 0) {
							popup.failure('文件类型超出可选范围,请重新选择');
							continue;
                        }
                    }

					// 在这里需要判断当前所有文件中
					if (this.selectedFilesCount >= this.options.maxUploadCount) {
						popup.failure('文件上传总数已达上限');
					} else {
						this.selectedFilesCount++;
						arrFiles.push(file);
					}
				}
			}
			return arrFiles;
		};
		/**
		 * 功能：调用核心插件
		 * 参数: 无
		 * 返回: 无
		 */
		this.createCorePlug = function () {
			var self = this;
			self.corePlugin.init({
				elemId: "#uploadForm",
				uploadUrl: self.options.url,
				uploadDataList: self.options.values,
				onFilterFile: function (files) {
					// 过滤合格的文件
					return self.funFilterEligibleFile(files);
				},	
				onSelect: function (selectFileDatas, allFileDatas) {
					self.options.onSelect(selectFileDatas, allFileDatas);  // 回调方法
					self.funSetStatusInfo(self.corePlugin.funGetUnuploadFiles());  // 显示统计信息
					var html = '';
					// 组织预览html
					layui.each(selectFileDatas, function (index, data) {
						const file = data.File;
						if (file) {
							html = '';
							var reader = new FileReader()
							reader.onload = function (e) {
								// 处理下配置参数和格式的html
								html = self.funDisposePreviewHtml(data, e);
								self.funAppendPreviewHtml(data, e, html);
							}
							reader.readAsDataURL(file);
                        }
					});
				},
				onDelete: function (delFileData, remainFileDatas) {
					//const $isUploaded = $("#uploadSuccess_" + delFileData.fileIndex);
					var isDeleteCbSuccess = self.options.onDelete(delFileData, remainFileDatas);

					if (isDeleteCbSuccess) {
						self.selectedFilesCount = remainFileDatas.length;
						// 移除效果
						$("#uploadList_" + delFileData.fileIndex).fadeOut();
						$("#uploadList_" + delFileData.fileIndex).remove();
						// 重新设置统计栏信息
						self.funSetStatusInfo(remainFileDatas);
						console.info("剩下的文件");
						console.info(remainFileDatas);
					}
				},
				onProgress: function (fileData, loaded, total) {
					var eleProgress = $("#uploadProgress_" + fileData.fileIndex),
						percent = (loaded / total * 100).toFixed(2) + '%';
					if (eleProgress.is(":hidden")) {
						eleProgress.show();
					}
					eleProgress.css("width", percent);
				},
				onSuccess: function (fileData) {
					$("#uploadProgress_" + fileData.fileIndex).hide();
					$("#uploadSuccess_" + fileData.fileIndex).show();
					self.options.onSuccess(fileData);
					//$("#uploadInf").append("<p>上传成功，文件地址是：" + response + "</p>");
				},
				onFailure: function (fileData, error) {
					$("#uploadProgress_" + fileData.fileIndex).hide();
					$("#uploadFailure_" + fileData.fileIndex).show();
					self.options.onFailure(fileData, error);
					//$("#uploadInf").append("<p>文件" + file.name + "上传失败！</p>");
				},
				onDragOver: function () {
					self.$Elem.find("#fileDragArea").addClass("upload_drag_hover");
				},
				onDragLeave: function () {
					self.$Elem.find("#fileDragArea").removeClass("upload_drag_hover");
				}
            });
		};
	};
	var _cssLink = "/lib/PearAdminLayui/component/pear/modules/zyUpload/dist/zyUpload.css";
	layui.link(_cssLink, function () {/*ignore*/ }, "layui-zyupload_css");
	var zyUpload = new zyUploadClass();
    //输出 mymod 接口
	exports('zyUpload', zyUpload);
});    